package demo.controller;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.micrometer.core.instrument.Metrics;

@RestController
public class GuageController {
    
    
    private static volatile Map<String,String> data = new ConcurrentHashMap<>();
    
    private static volatile CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

    
    static {
        
        Metrics.gauge("guageDataMapSize", data, Map::size);
        Metrics.gauge("guageDataMapSize2", data, GuageController::mapsizeStatic);
        Metrics.gauge("guageDataListSize", list, List::size);

    }
    
	
	@RequestMapping({"/guageDataUpdate"})
	public Object guageDataUpdate(HttpServletRequest request)throws Exception{
	    
	    String value = LocalDateTime.now().toString();
	    data.put(value, value);
	    list.add(value);
	    
	    if(data.size() > 7) {
	        //
	        data.clear();
	        // data = new ConcurrentHashMap<>();
	        list.clear();
	    }
	    
        Metrics.gauge("guageDataMapSize3", data, this::mapsize);
		
		return data;
	}
	
	
	@RequestMapping({"/addGuageMetric"})
    public Object addGuageMetric(HttpServletRequest request)throws Exception{
        
       
        Map<String,String> map = Metrics.gauge("guageDataMapSize3", data, this::mapsize);
        
        
        Metrics.gauge("guageDataListSize7", "guageDataListSize7", this::getByName);
        Metrics.gauge("guageDataMapSize7", "guageDataMapSize7", this::getByName);

        
        return map;
    }
	
	private int mapsize(Map map) {
	    return map.size();
	}
	
	private static int mapsizeStatic(Map map) {
        return map.size();
    }
	
	private int getByName(String name) {
	    if(name.equals("guageDataMapSize7")) {
	        return data.size();
	    }
	    if(name.equals("guageDataListSize7")) {
            return list.size();
        }
	    return 0;
	}
}